//
//  EmoticonViewController.swift
//  EmotiDemo
//
//  Created by leador on 17/5/16.
//  Copyright © 2017年 袁满. All rights reserved.
//

import UIKit

private let EmoticonCell = "EmoticonCell"

class EmoticonViewController: UIViewController {

    var emoticonCallBack : (_ emoticon:Emoticon)->()
    
    lazy var collectionView:UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout:EmoticonCollectionLayout())
    lazy var toolBar:UIToolbar = UIToolbar()
    lazy var manager:EmoticonManager = EmoticonManager()
    
    init(emoticonCallBack:@escaping (_ emoticon:Emoticon)->()) {
        
        self.emoticonCallBack = emoticonCallBack
        
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
    
}

//MARK: ---UI界面---
extension EmoticonViewController {
    
    func setupUI() {
        
        view.addSubview(collectionView)
        view.addSubview(toolBar)
        
        collectionView.backgroundColor = UIColor.blue
        toolBar.backgroundColor = UIColor.red
        
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        
        let views:[String:Any] = ["toolBar":toolBar,"collectionView":collectionView]
        var cons = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[toolBar]-0-|", options: [], metrics: nil, views: views)
        
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[collectionView]-0-[toolBar]-0-|", options: [.alignAllLeft,.alignAllRight], metrics: nil, views: views)
        view.addConstraints(cons)
        
        prepareForCollectionView()
        prepareForToolBar()
    }
    
    private func prepareForCollectionView() {
        
        collectionView.register(EmoticonCollectionViewCell.self, forCellWithReuseIdentifier: EmoticonCell)
        collectionView.dataSource = self
        collectionView.delegate = self
        
    }
    
    private func prepareForToolBar() {
        
        let titles = ["最近","默认","emoji","浪小花"]
        
        var tempItems = [UIBarButtonItem]()
        var index = 0
        for title in titles {
            
            let item = UIBarButtonItem(title: title, style: .plain, target: self, action: #selector(itemClick))
            let it = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)

            tempItems.append(item)
            tempItems.append(it)
            
            item.tag = index
            
            index = index + 1
            
        }
        
        tempItems.removeLast()
        
        toolBar.tintColor = UIColor.orange
        toolBar.items = tempItems
        
    }
    
    @objc private func itemClick(item:UIBarButtonItem) {
        let indexPath = IndexPath(item: 0, section: item.tag)
        collectionView.scrollToItem(at: indexPath, at: .left, animated: true)
    }
    
}

extension EmoticonViewController:UICollectionViewDataSource,UICollectionViewDelegate {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return manager.packages.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let package = manager.packages[section]
        return package.emoticons.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmoticonCell, for: indexPath) as! EmoticonCollectionViewCell
        
        let package = manager.packages[indexPath.section]
        cell.emoticon = package.emoticons[indexPath.row]
        
        return cell
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
        let package = manager.packages[indexPath.section]
        let emoticon = package.emoticons[indexPath.row]
        
        //MARK: ---数据传递---
        self.emoticonCallBack(emoticon)
        
        //MARK: ---将表情添加到最近分组中---
        if emoticon.isEmpty || emoticon.isRemove {
            return
        }
        
        if manager.packages.first!.emoticons.contains(emoticon) {
            let index = (manager.packages.first!.emoticons.index(of: emoticon))!
            manager.packages.first!.emoticons.remove(at: index)
        }else {
            manager.packages.first!.emoticons.remove(at: 19)
        }
        
        manager.packages.first?.emoticons.insert(emoticon, at: 0)
        
        
        
    }
    
}

class EmoticonCollectionLayout:UICollectionViewFlowLayout {
    
    override func prepare() {
        
        super.prepare()
        
        let itemWH = UIScreen.main.bounds.width / 7
        
        itemSize = CGSize(width: itemWH, height: itemWH)
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = .horizontal
        
        collectionView?.isPagingEnabled = true
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.showsHorizontalScrollIndicator = false
        
        let insetMargin = (collectionView!.bounds.height-3*itemWH) / 2
        collectionView?.contentInset = UIEdgeInsetsMake(insetMargin-1, 0, insetMargin, 0)
        
    }
    
}
